<template>
	<a-select ref="select" :placeholder="placeholder"
		:value="record[keyObj.keyName] ? record[keyObj.displayName1] + ' ' + (record[keyObj.displayName2] ? record[keyObj.displayName2] : '') : undefined"
		style="width: 100%;" :dropdownMatchSelectWidth="false" showSearch :disabled="disabled" @search="onSearch"
		@focus="getData">
		<div slot="dropdownRender">
			<div style="padding: 4px 8px; cursor: pointer;" @mousedown="mousedown">
				<a-table ref="table" bordered size="middle" :rowKey="keyObj.keyName" :columns="columns"
					:dataSource="dataSource" :pagination="ipagination" :loading="loading" @change="handleTableChange"
					:customRow="customRowFun"></a-table>
			</div>
		</div>
	</a-select>
</template>

<script>
	import {
		postAction,
		getAction
	} from '@/api/manage';
	import {
		filterObj
	} from '@/utils/util';

	export default {
		name: 'tableselect',
		data() {
			return {
				record: {},
				dataSource: [],
				selectedRowKeys: [],
				selectionRows: [],
				queryParam: {},
				timeout: null,
				currentName: undefined,
				/* table加载状态 */
				loading: false,
				/* 分页参数 */
				ipagination: {
					current: 1,
					pageSize: 10,
					pageSizeOptions: ['10', '20', '30'],
					showTotal: (total, range) => {
						return range[0] + '-' + range[1] + ' 共' + total + '条';
					},
					showQuickJumper: false,
					showSizeChanger: false,
					total: 0
				}
			};
		},
		// 默认情况下，一个组件上的 v-model 会把 value 用作 prop 且把 input 用作 event
		model: {
			prop: 'value',
			event: 'chooseItem'
		},
		props: {
			value: {
				type: Object
				// 这个参数是v-decorator给子组件传值用的
				// 这里不要给默认值， 在form下使用会爆警告
			},
			// 访问地址
			url: {
				type: String,
				default: '/basicinfo/elder/page'
			},
			requestMethod: {
				type: String,
				default: 'post'
			},
			disabled: {
				type: Boolean,
				default: false
			},
			placeholder: {
				type: String,
				default: '请选择长者'
			},
			keyObj: {
				type: Object,
				default: () => ({
					keyName: 'elderId',
					displayName1: 'name',
					displayName2: 'mobilephone'
				})
			},
			ids: {
				type: Array,
				default: () => []
			},
			enabled: {
				type: Boolean,
				default: true
			},
			columns: {
				type: Array,
				default: () => [{
						title: '姓名',
						align: 'center',
						width: 100,
						dataIndex: 'name'
					},
					{
						title: '性别',
						align: 'center',
						width: 50,
						dataIndex: 'sex',
						customRender: function(text) {
							if (text == 1 || text == '男') {
								return '男';
							} else {
								return '女';
							}
						}
					},
					{
						title: '年龄',
						align: 'center',
						width: 50,
						dataIndex: 'age'
					},
					{
						title: '手机号码',
						align: 'center',
						width: 100,
						dataIndex: 'mobilephone'
					}
				]
			}
		},
		watch: {
			// 监听父组件传递过来的图片列表信息
			value: {
				deep: true,
				immediate: true,
				handler: function(newV) {
					console.log(newV);
					if (!newV) {
						this.record = {};
					} else {
						this.record = newV;
					}

				}
			}
		},
		methods: {
			// select搜索，按照长者名字搜索
			onSearch(v) {
				console.log(v);
				this.queryParam[this.keyObj.displayName1] = v;
				this.fetch();
			},
			// 输入完成300毫秒搜索
			fetch() {
				if (this.timeout) {
					clearTimeout(this.timeout);
					this.timeout = null;
				}
				this.currentName = this.queryParam[this.keyObj.displayName1];
				this.timeout = setTimeout(this.loadData, 300);
			},
			// 鼠标点击事件，如果点击分页，就不收回下拉，点击长者收回下来
			mousedown(e) {
				// console.log(e.target.localName);
				// console.log(e.toElement.nodeName);
				if (e.target.localName == 'a' || e.target.localName == 'svg') {
					e.preventDefault();
				}
			},
			// 自定义列表项，点击长者列表的时候触发click
			customRowFun(record) {
				return {
					on: {
						click: event => {
							console.log(record, event);
							// this.record = record;
							this.$refs.select.blur(); //取消焦点blur(), 获取焦点focus()
							// console.log(this.$refs.select);
							// 向父组件更新
							console.log(this.record[this.keyObj.keyName])
							console.log(this.record[this.keyObj.displayName1])
							this.$emit('chooseItem', Object.assign({}, record));
						}
					}
				};
			},
			//分页、排序、筛选变化时触发
			handleTableChange(pagination) {
				this.ipagination = pagination;
				this.loadData();
			},
			//获取查询条件，查询长者姓名
			getQueryParams() {
				let sqp = {};
				var param = Object.assign(sqp, this.queryParam);
				param.current = this.ipagination.current;
				param.size = this.ipagination.pageSize;
				this.ids.forEach(item => {
					param[item.key] = item.value
				})
				console.log(param)
				console.log(filterObj(param))
				return filterObj(param);
			},
			// 根据查询条件，分页查询长者信息
			loadData() {
				if (!this.url) {
					this.$message.error('请设置url属性!');
					return;
				}
				var params = this.getQueryParams(); //查询条件
				this.loading = true;
				console.log(params);
				if (this.requestMethod == 'get') {
					//仅在居家服务项目获取项目类型中使用
					getAction(this.url).then(res => {
						if (res.code == '00000') {
							if (this.currentName == this.queryParam[this.keyObj.displayName1]) {
								console.log('搜索成功:\t', this.currentName, this.queryParam[this.keyObj
								.displayName1]);
								this.dataSource = res.data
								this.selectedRowKeys = [];
							} else {
								console.log('搜索关键词已经变化:\t', this.currentName, this.queryParam[this.keyObj
									.displayName1]);
							}
						} else {
							this.$message.warning("获取数据失败")
						}
						this.loading = false;
					})
				} else {
					postAction(this.url, params).then(res => {
						if (res.code == '00000') {
							if (this.currentName == this.queryParam[this.keyObj.displayName1]) {
								console.log('搜索成功:\t', this.currentName, this.queryParam[this.keyObj
								.displayName1]);
								this.dataSource = res.data.records;
								this.ipagination.total = res.data.total;
								this.selectedRowKeys = [];
							} else {
								console.log('搜索关键词已经变化:\t', this.currentName, this.queryParam[this.keyObj
									.displayName1]);
							}
						} else {
							this.$message.warning("获取数据失败")
						}
						this.loading = false;
					});
				}
			},
			getData() {
				if (this.enabled) {
					this.loadData();
				} else {
					if (this.ids.length > 0) {
						this.loadData();
					}
				}
			}
		},
		mounted() {
			// console.log('url', this.url);
			// console.log('columns', this.columns);
			// console.log('keyObj', this.keyObj);
			// console.log(this.value);
			// this.loadData();
			if (this.enabled) {
				this.loadData();
			}
		}
	};
</script>

<style lang="less" scoped></style>
